package a.b.reggie.service.impl;

import a.b.reggie.mapper.ShoppingCartMapper;
import a.b.reggie.pojo.ShoppingCart;
import a.b.reggie.pojo.User;
import a.b.reggie.service.IShoppingCartService;
import a.b.reggie.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class IShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements IShoppingCartService {

    @Autowired
    private IUserService userService;

    /**
     * 向购物车添加食品
     * @param phone
     * @param shoppingCart
     */
    @Transactional
    public void addFood(String phone, ShoppingCart shoppingCart) {
        //根据手机号查询用户id
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone,phone);
        User user = userService.getOne(queryWrapper);
        Long userId = user.getId();

        //设置购物车的使用者id
        shoppingCart.setUserId(userId);

        //获取食品id
        Long DishId = shoppingCart.getDishId();

        //根据食品id查询是否有同种食物
        LambdaQueryWrapper<ShoppingCart> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(ShoppingCart::getDishId,DishId);
        ShoppingCart cart = this.getOne(queryWrapper1);
        if (cart==null){
            //若没有则直接添加
            this.save(shoppingCart);
        }else {
            //若有则不添加，只改变数量
            cart.setNumber(cart.getNumber()+1);
            //保存修改后的购物车
            this.updateById(cart);
        }

    }

    /**
     * 减少食品数量
     * @param  DishId
     */
    public void sub(Long DishId) {
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getDishId, DishId);
        ShoppingCart cart = this.getOne(queryWrapper);
        //减少菜品数量
        cart.setNumber(cart.getNumber()-1);
        //判断菜品数量
        if (cart.getNumber()==0){
            //若等于0则直接删除该菜品
            this.remove(queryWrapper);
        }else {
            //若不等于0,保存修改后的购物车
            this.updateById(cart);
        }
    }

}
